<?php

require_once ('IMessageService.php');
require_once ('BaseService.php');
require_once 'util/ServiceUtil.php';
require_once 'util/StringUtil.php';
require_once 'dao/MessageDao.php';

class MessageService extends BaseService implements IMessageService {
	public static $NAME = "MessageService";
	protected $message;
	public function MessageService() {
		$this->initializeDB();
		$this->message = new MessageDao();
	}
	
	public function create(MessageDao $object) 
	{
		if($object)
		{
			try
			{
				$this->sql = "INSERT INTO message(content,messager,pid,title) VALUES('$object->content','$object->messager',
													'$object->pid','$object->title')";
				$this->query = mysql_query($this->sql,$this->myDb);
				return $this->checkQueryResult(mysql_affected_rows($this->myDb));
			}catch(Exception $exc)
			{
				return $exc;
			}
		}
		return NULL;
	}
	
	public function delete($id) 
	{
		if($id)
		{
			try
			{
				$this->sql = "DELETE * FROM message WHERE id = '$id'";
				$this->query = mysql_query($this->sql,$this->myDb);
				return $this->checkQueryResult(mysql_affected_rows($this->myDb));
			}catch(Exception $exc)
			{
				return $exc;
			}
		}
		return NULL;
	}
	
	public function read($id) 
	{
		if($id==NULL||$id==-1)
		{
			$this->sql = "SELECT * FROM message";
		}else
		{
			$this->sql = "SELECT * FROM message WHERE id='$id'";
		}
		try
		{
			$this->query = mysql_query($this->sql,$this->myDb);
			$this->numRows = mysql_num_rows($this->query);
			
			for($i=0;$i<$this->numRows;$i++)
 			{
 				$row = mysql_fetch_object($this->query);
 				
 				$this->message->id = $row->id;
				$this->message->pid = $row->pid;
				$this->message->messager = $row->messager;
				$this->message->title = $row->title;
				$this->message->content = $row->content;
				$this->message->time = $row->time;
					
				$this->result[] = $this->message;
 			}
			return $this->result;
		}catch(Exception $exc)
		{
			return $exc;
		}
		return NULL;
	}
	
	public function update(MessageDao $object) 
	{
		if ($object) 
		{
			try
			{
				$this->sql = "UPDATE TABLE message SET message.messager = '$object->messager',
								messager.title='$object->title',messager.content='$object->content'";
				$this->query = mysql_query($this->sql,$this->myDb);
				return $this->checkQueryResult(mysql_affected_rows($this->myDb));
			}catch(Exception $exc)
			{
				return $exc;
			}
		}
		return NULL;
	}
}

?>